package com.xc.ezplan.admin.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.xc.ezplan.admin.entity.AdminEmailConfig;
import com.xc.ezplan.admin.mapper.AdminEmailConfigMapper;
import com.xc.ezplan.admin.service.AdminEmailService;
import com.xc.ezplan.admin.vo.AdminEmailVo;
import com.xc.ezplan.core.exception.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author lixingchen
 * @date 2022/12/17
 * @description 邮件实现类
 */
@Service
@RequiredArgsConstructor
public class AdminEmailServiceImpl implements AdminEmailService {
    private final AdminEmailConfigMapper adminEmailConfigMapper;

    @Override
    public void sendEmail(AdminEmailVo adminEmailVo) {
        Integer configId = adminEmailVo.getConfigId();
        AdminEmailConfig adminEmailConfig = adminEmailConfigMapper.selectById(configId);
        // 封装
        MailAccount account = new MailAccount();
        // 设置用户
        String user = adminEmailConfig.getFromUser().split("@")[0];
        account.setUser(user);
        account.setHost(adminEmailConfig.getHost());
        account.setPort(Integer.parseInt(adminEmailConfig.getPort()));
        account.setAuth(true);
        try {
            // 对称解密
            account.setPass(adminEmailConfig.getPass());
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
        account.setFrom(adminEmailConfig.getUser()+"<"+adminEmailConfig.getFromUser()+">");
        // ssl方式发送
        account.setSslEnable(true);
        // 使用STARTTLS安全连接
        account.setStarttlsEnable(true);
        String content = adminEmailVo.getContent();
        // 发送
        try {
            int size = adminEmailVo.getTos().size();
            Mail.create(account)
                    .setTos(adminEmailVo.getTos().toArray(new String[size]))
                    .setTitle(adminEmailVo.getSubject())
                    .setContent(content)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        }catch (Exception e){
            throw new BadRequestException(e.getMessage());
        }
    }
}
